package com.jiangnan.repository

import com.jiangnan.api.client.ApiClient
import com.jiangnan.api.client.BookApiClient
import com.jiangnan.entity.LoginInfo
import com.jiangnan.entity.Res
import com.jiangnan.entity.User
import okhttp3.MultipartBody
import retrofit2.Response

class AuthRepository {

    /**
     * 调用发送验证码接口
     */
    suspend fun sendSmsCode(phone: String): Res<Any> {
        return try {
            val response = ApiClient.apiCall { BookApiClient.authApiService.sendCode(phone) }
            if (response.isSuccessful) {
                response.body() ?: Res(0, "返回为空", null)
            } else {
                Res(0, "网络错误：${response.code()}", null)
            }
        } catch (e: Exception) {
            Res(0, e.message ?: "未知错误", null)
        }
    }

    /**
     * 调用注册接口
     */
    suspend fun registerUser(phone: String, password: String, smsCode: String): Res<Any> {
        return try {
            val response = ApiClient.apiCall { BookApiClient.authApiService.register(phone, password, smsCode) }
            if (response.isSuccessful) {
                response.body() ?: Res(0, "返回为空", null)
            } else {
                Res(0, "网络错误：${response.code()}", null)
            }
        } catch (e: Exception) {
            Res(0, e.message ?: "未知错误", null)
        }
    }

    /**
     * 登录请求，返回 Res<User>
     */
    suspend fun loginUser(phone: String, password: String): Res<LoginInfo> {
        return BookApiClient.apiCall { BookApiClient.authApiService.login(phone, password) }
    }

    /**
     * 调用忘记密码接口，重置密码
     */
    suspend fun resetPassword(phone: String, smsCode: String, newPassword: String): Res<Any> {
        return try {
            val response = BookApiClient.authApiService.resetPassword(phone, smsCode, newPassword)
            if (response.isSuccessful) {
                response.body() ?: Res(0, "返回为空", null)
            } else {
                Res(0, "网络错误：${response.code()}", null)
            }
        } catch (e: Exception) {
            Res(0, e.message ?: "未知错误", null)
        }
    }

    /**
     * 上传图片接口，返回图片地址
     */
    suspend fun uploadImage(file: MultipartBody.Part): Response<Res<String>> {
        return BookApiClient.bookApiService.uploadImage(file)
    }
}